package com.example.prison.util;

import com.example.prison.service.CommonService;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import java.net.InetSocketAddress;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class TCPClientHandler extends SimpleChannelInboundHandler<String> {
   private final Logger logger = LoggerFactory.getLogger(TCPClientHandler.class);
   CommonService commonService = (CommonService)SpringUtil.getBean(CommonService.class);

   @Override
   public void channelActive(ChannelHandlerContext ctx) throws Exception {
      InetSocketAddress insocket = (InetSocketAddress)ctx.channel().remoteAddress();
      String clientIp = insocket.getAddress().getHostAddress();
      int port = insocket.getPort();
      this.logger.info("连接到服务器[ip:" + clientIp + "：" + port + "]");
   }

   @Override
   public void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
      System.out.println(msg);
      this.commonService.intoRabbitMq(msg);
   }

   @Override
   public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
      cause.printStackTrace();
      ctx.close();
   }
}
